package com.example.fragment_demo1;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.widget.RadioGroup;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

/**
 * fragment 测试
 *
 * @author MAC
 */
public class MainActivity extends FragmentActivity {

    private final String TAG = "MainActivity";

    private RadioGroup mRadioGroup;
    private Fragment1 mF1;
    private Fragment2 mF2;
    private Fragment3 mF3;

    private FragmentTransaction transaction;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        setupWidgets();
    }

    private void init() {
        transaction = getSupportFragmentManager().beginTransaction();
        if (null == mF1) {
            mF1 = new Fragment1();
        }
        transaction.add(R.id.fragment_container, mF1);
        transaction.commit();
    }

    @SuppressLint("NonConstantResourceId")
    private void setupWidgets() {
        mRadioGroup = findViewById(R.id.radioGroup1);
        mRadioGroup.setOnCheckedChangeListener(((group, checkedId) -> {
            switch (checkedId) {
                case R.id.radio0:
                    Log.v(TAG, "setupWidgets():radio0 clicked");
                    if (null == mF1) {
                        Log.v(TAG, "new Fragment1");
                        mF1 = new Fragment1();
                    }
                    transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.fragment_container, mF1);
                    transaction.commit();
                    break;
                case R.id.radio1:
                    Log.v(TAG, "setupWidgets():radio1 clicked");
                    if (null == mF2) {
                        Log.v(TAG, "new Fragment2");
                        mF2 = new Fragment2();
                    }
                    transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.fragment_container, mF2);
                    transaction.commit();
                    break;
                case R.id.radio2:
                    Log.v(TAG, "setupWidgets():radio2 clicked");

                    if (null == mF3) {
                        Log.v(TAG, "new Fragment3");
                        mF3 = new Fragment3();
                    }
                    transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.fragment_container, mF3);
                    transaction.commit();
                    break;

                default:
                    break;
            }
        }));
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}